package javabase.concurrent;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 两者同时到达后才会交换数据
 *
 */
public class ExchangerDemo {
	
	public static void main(String[] args) {
		ExecutorService service = Executors.newFixedThreadPool(2);
		
		Exchanger<String> exchanger = new Exchanger<>();
		
		service.execute(() -> {
			try {
				String data1 = "huanghe";
				System.out.println(Thread.currentThread().getName() + data1);
				String data2 =  exchanger.exchange(data1);
				System.out.println(Thread.currentThread().getName() + data2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		});

		
		service.execute(() -> {
			try {
				String data1 = "changjiang";
				System.out.println(Thread.currentThread().getName() + data1);
				String data2 =  exchanger.exchange(data1);
				System.out.println(Thread.currentThread().getName() + data2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		});
		
	}
	
	
}
